<?php
    //все внешние запросы будут проходить через этот класс
    class http
    {
        /* 
        file_get_contents
        curl
        socket 
        * 
        */
        static $remote_type = 'curl'; 
        static $timeout   = 6;     // Сколько ждать ответа
        static $user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)';

        static $all_useragents = array();
        static $ssl = false;

        //отправка методом post
        static $postfields = array();
        static $postfields_str = '';

        static $proxy = '';

        //куки для curl
        static $cookie = false;
        static $cookie_name = '';

        static $header; 

        //кол попыток
        static $try = 1;
        //время спячки между попытками
        static $sleep = 10;

        //
        static $info;
        //подробная информация о запросе
        static $report;

        static $X_Requested_With = '';

        static $referer = '';
        static $code = '';
        static $log = array();


        public static function free ($url)
        {
            $cookie_name = @ parse_url( $url );
            $host =  @ $cookie_name ['host'];
            $host = str_replace('www.', '', $host);

            $_cookie_name = "cookie.".@$host.".txt";

            m::json_data_save( $_cookie_name,   array());
        }


        public static function get( $url, $param = array())
        {
            for ($i =0; $i<=self::$try; $i++)
            {
                $data = self::get2($url, $param); 

                if ( !empty($data) and self::$code == 200)
                {
                    return $data; 
                }
                elseif (self::$code=='302')
                {
                    /*$data = self::get2(self::$info['redirect_url'], $param); 

                    if ( !empty($data) and self::$code == 200)
                    {
                    return $data; 
                    }
                    */
                }

            }

            return $data;


            // return self::get2($url, $param);  
        }

        public static function get2( $url, $param = array())
        {
            @ini_set('allow_url_fopen',          1);
            @ini_set('default_socket_timeout',   self::$timeout);
            @ini_set('user_agent',               self::$user_agent);

            $http_headers = array();
            if ($ch = curl_init()) 
            {               

                $cookie_name = @ parse_url( $url );
                $host =  @ $cookie_name ['host'];
                $host = str_replace('www.', '', $host);

                $_cookie_name  = '';
                //массив кук
                $co = array();

                if ( !empty( self::$cookie_name ) )
                {
                    $_cookie_name = "cookie.".self::$cookie_name.".txt"; 
                }    
                else
                {
                    $_cookie_name = "cookie.".@$host.".txt";
                }

                if (  self::$cookie )
                {

                    curl_setopt($ch, CURLOPT_COOKIEJAR, DATA_PATH.$_cookie_name);
                    curl_setopt($ch, CURLOPT_COOKIEFILE,  DATA_PATH.$_cookie_name);
                }


                if ( !empty( self::$X_Requested_With ) )
                {   
                    $http_headers[] =  "X-Requested-With: ".self::$X_Requested_With;   
                }


                if ( !empty( self::$referer ) )
                {
                    $http_headers[] =  "Referer: ".self::$referer;  
                }


                if ( is_array( $http_headers) and count($http_headers) > 0)
                {
                   curl_setopt($ch, CURLOPT_HTTPHEADER, $http_headers);  
                }



                @ curl_setopt($ch, CURLOPT_URL,              $url);
                @ curl_setopt($ch, CURLOPT_HEADER,           1);

                @ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                //  @ curl_setopt($ch, CURLINFO_HEADER_OUT,1 );
                @ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,   self::$timeout);
                @ curl_setopt($ch, CURLOPT_TIMEOUT,          self::$timeout);
                @ curl_setopt($ch, CURLOPT_USERAGENT,        self::$user_agent);
                @ curl_setopt($ch, CURLOPT_ENCODING, "gzip, deflate, identity"); 



                //если есть поля для post - отправляем их
                if ( is_array( self::$postfields ) && count( self::$postfields ) > 0 )
                {
                    curl_setopt($ch, CURLOPT_POST, 1);
                    //  curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);

                    $postdata = '';
                    foreach ( self::$postfields as $key => $value ) $postdata .= "&".rawurlencode($key)."=".rawurlencode($value);
                    $postdata = substr( $postdata, 1 );

                    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                }
                if ( !empty( self::$postfields_str))
                {
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, self::$postfields_str);
                }

                //ssl = true
                if ( self::$ssl == true )
                {
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                }

                if ( !empty(self::$proxy) )
                {
                    curl_setopt($ch, CURLOPT_PROXY, self::$proxy);
                    //  curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
                }


                if ($data = curl_exec($ch)) 
                {
                    //  echo $data;
                    self::$info = curl_getinfo($ch);

                    $header=substr($data,0,curl_getinfo($ch,CURLINFO_HEADER_SIZE));
                    // echo $data;
                    $body=substr($data,curl_getinfo($ch,CURLINFO_HEADER_SIZE));
                    preg_match_all("/Set-Cookie: (.*?)=(.*?);/i",$header,$res);
                    self::$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                    @curl_close($ch);

                    return $body;  

                    /* if ( empty( $data ) )
                    {

                    if ( self::$try == 1 )
                    {
                    @curl_close($ch);
                    return false; 
                    }
                    else
                    {
                    for ($i==2; $i <= self::$try; $i++  )
                    {            
                    $data = @curl_exec($ch);

                    self::$info = curl_getinfo($ch);

                    if ( !empty( $data ) )
                    {
                    @curl_close($ch);
                    return $data;
                    }

                    self::$report[] = 'Попытка '.$i.'. Ответ пустой';

                    sleep( self::$sleep );
                    }

                    @curl_close($ch);
                    return false;
                    }
                    }
                    else
                    {
                    //self::$info = curl_getinfo($ch);

                    @curl_close($ch);
                    return $body;  
                    }

                    */

                }

                @curl_close($ch);


            }





            return false;
        }

        public static function clear_cookie ($name)
        {

        }


        public static function get_report()
        {
            return self::$report;   
        }
    }
?>
